﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace LVYAN.Utils
{
    /// <summary>
    /// 
    /// </summary>
    public class RequestService
    {
        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">请求数据</param>
        /// <returns>HTTP响应</returns>
        public string PostJson(string url, string data, List<(string, string)> headers = default)
        {
            string result = "";
            try
            {
                if (string.IsNullOrWhiteSpace(url))
                {
                    return "";
                }
                HttpWebRequest req = GetWebRequest(url, "POST");
                req.ContentType = "application/json;utf-8";
                if (headers != null)
                {
                    foreach (var item in headers)
                    {
                        req.Headers.Add(item.Item1, item.Item2);
                    }
                }
                byte[] postData = Encoding.UTF8.GetBytes(data);
                Stream reqStream = req.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                reqStream.Close();
                HttpWebResponse rsp = null;
                rsp = (HttpWebResponse)req.GetResponse();
                result = GetResponseAsString(rsp, Encoding.UTF8);
            }
            catch (Exception ex)
            {

            }
            return result;
        }
        private HttpWebRequest GetWebRequest(String url, String method)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = method;
            return req;
        }
        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        private string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            Stream stream = null;
            StreamReader reader = null;
            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);
                return reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                return "";
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">请求数据</param>
        /// <returns>HTTP响应</returns>
        public async Task<string> Upload(string url, string ImgPath)
        {
            string result = "";
            try
            {
                using (var client = new HttpClient())
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        // 假设服务器期望的文件字段名为"file"  
                        var fileContent = new ByteArrayContent(File.ReadAllBytes(ImgPath));
                        // 根据你的图片类型设置
                        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");
                        // "file"是表单字段名，"image.jpg"是文件名，可以自定义  
                        content.Add(fileContent, "file", "image.png");
                        content.Add(new StringContent("robot"), "module");
                        content.Add(new StringContent("robot"), "type");
                        content.Add(new StringContent("robot"), "TenantID");
                        content.Add(new StringContent("true"), "IsOss");
                        content.Add(new StringContent("365"), "OssDay");

                        try
                        {
                            var response = await client.PostAsync(url, content);
                            response.EnsureSuccessStatusCode(); // 确保HTTP成功状态值  
                            result = Encoding.UTF8.GetString(await response.Content.ReadAsByteArrayAsync());
                        }
                        catch (HttpRequestException e)
                        {
                            Console.WriteLine("\nException Caught!");
                            Console.WriteLine("Message :{0} ", e.Message);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return result;
        }


        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">图片请求地址</param>
        /// <param name="data">请求数据</param>
        /// <returns>HTTP响应</returns>
        public async Task<bool> Down(string url, string ImgPath)
        {
            var result = true;
            try
            {
                string directoryName = Path.GetDirectoryName(ImgPath);
                if (!Directory.Exists(directoryName))
                {
                    Directory.CreateDirectory(directoryName);
                }
                using (HttpClient client = new HttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
                    response.EnsureSuccessStatusCode(); // 确保HTTP成功状态值  

                    // 读取响应内容  
                    Stream contentStream = await response.Content.ReadAsStreamAsync();

                    // 写入到本地文件  
                    using (FileStream fileStream = new FileStream(ImgPath, FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        await contentStream.CopyToAsync(fileStream);
                    }
                }
            }
            catch (HttpRequestException e)
            {
                result = false;
                Console.WriteLine("\n异常捕获: {0}", e.Message);
            }
            return result;
        }


    }
}
